package net.lcqf.udp.game;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.PooledByteBufAllocator;
import net.lcqf.udp.kcp.Ukcp;
import net.lcqf.udp.response.NtfOpKeyResponse;
import net.lcqf.udp.send.MessageFactory;
import net.lcqf.udp.send.RequestType;
import net.lcqf.udp.server.MsgInfo;
import net.lcqf.udp.utils.LocalCacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/3/20 11:01
 * // +----------------------------------------------------------------------
 */
public class RoomManager {

    private static final Logger logger = LoggerFactory.getLogger(RoomManager.class);

    // 使用 PooledByteBufAllocator（池化）
    private final ByteBufAllocator allocator = PooledByteBufAllocator.DEFAULT;
    private final Integer roomId;
    private final List<String> channelList;

    public final List<String> opKeyList;

    private final ScheduledExecutorService scheduler;

    // 每66毫秒发送15帧的数据
    public final int CLIENT_LOGIC_FRAME_DELTA_SEND = 66;
    public int frameId = 0;

    public RoomManager(Integer roomId, List<String> channelList, List<String> opKeyList) {
        scheduler = Executors.newScheduledThreadPool(1, r -> new Thread(r, "sendOpKey-" + roomId));
        this.roomId = roomId;
        this.channelList = channelList;
        this.opKeyList = opKeyList;

        startSendOpKeyTimer();
    }


    public void addChannel(String channelId) {
        channelList.add(channelId);
    }

    public void addOpKey(String opKey) { opKeyList.add(opKey); }


    private void startSendOpKeyTimer(){
        scheduler.scheduleAtFixedRate(this::executeTask, 0, CLIENT_LOGIC_FRAME_DELTA_SEND, TimeUnit.MILLISECONDS);
    }

    /**
     * TODO 玩家移动、玩家释放技能
     */
    private void executeTask() {
        //logger.info("间隔66毫秒发送一次(玩家移动、玩家释放技能)数据");
        ++frameId;
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setRequestType(RequestType.SEND_OP_KEY.getCustomOrdinal());

        NtfOpKeyResponse response = new NtfOpKeyResponse();
        response.setFrameId(frameId);
        if (opKeyList.size() > 0) { response.setKeyList(opKeyList); }
        String data = JSONUtil.toJsonStr(response);
        msgInfo.setData(data.replace("\"{","{").replace("}\"","}").replace("\\\"","\""));
        //logger.info("玩家操作数据：{}", opKeyList);
        opKeyList.clear();
        broadcastToPlayer(msgInfo);

    }

    /**
     * 发送指定房间的玩家
     * @param msgInfo 消息内容
     */
    public void broadcastToPlayer(MsgInfo msgInfo) {
        for (String chanelId : channelList) {
            Ukcp kcp = LocalCacheUtil.USER_KCP.get(chanelId);

            if (kcp.isActive()) {
                ByteBuf byteBuf = MessageFactory.serializeToByteBuf(JSONUtil.toJsonStr(msgInfo));
                kcp.write(byteBuf);
                byteBuf.release();
            }
        }
    }
}
